package com.dangz.dans.utils;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JDBCUtils： 数据库连接工具
 * @author dangz
 * @since 2018/4/3 15:27
 */
public class JDBCUtils {
    /**
     * 使用数据库连接池  比不使用效率高三分之二左右
     */
    private static final DruidDataSource druidDataSource = new DruidDataSource();

    private static Connection con = null;
    /**
     * MethonName: setConnection
     * 建立连接
     * @params:  [url, userName, pwd, type]
     * @return:  java.sql.Connection
     *
     * @author: dangz
     * @since: 2018/4/3 15:30
     */
    public static Connection setConnection(String url, String userName, String pwd, String type) {
        try {
            if ("oracle".equals(type)) {
//                Class.forName("oracle.jdbc.driver.OracleDriver"); // 加载Oracle驱动程序
                druidDataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
            } else if ("mysql".equals(type)){
//                Class.forName("com.mysql.jdbc.Driver"); // 加载mysql驱动程序
                druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            }
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(userName);
            druidDataSource.setPassword(pwd);
//            con = DriverManager.getConnection(url, userName, pwd);// 获取连接
            con = druidDataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("get connection error !", e);
        }
        return con;
    }

    /**
     * MethonName: close
     * 关闭
     * @params:  [rs]
     * @return:  void
     *
     * @author: dangz
     * @since: 2018/4/3 15:42
     */
    public static void closeConnection(PreparedStatement psmt, ResultSet result) {
        try {
            if (null != result) {
                result.close();
            }
            if (null != psmt) {
                psmt.close();
            }
            if (null != con) {
                con.close();
            }
        } catch (SQLException e){
            throw new RuntimeException("close connection error !", e);
        }
    }
}
